<template>
  <el-dialog
    :title="$t('msg.excel.roleDialogTitle')"
    :model-value="modelValue"
    @close="closed"
  >
    <el-checkbox-group v-model="userRoleTitleList">
      <el-checkbox
        v-for="item in allRoleList"
        :key="item.id"
        :label="item.title"
      ></el-checkbox>
    </el-checkbox-group>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="closed">取消</el-button>
        <el-button type="primary" @click="onConfirm">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { defineProps, defineEmits, ref } from 'vue'
import { roleList } from '@/api/user'
import { useUserStore } from '@/store'

const props = defineProps({
  modelValue: { type: Boolean, required: true },
  userId: { type: String, required: true }
})
const emits = defineEmits(['update:modelValue', 'updateRole'])

// 获取角色数据
const allRoleList = ref([])
const getRoleList = async () => (allRoleList.value = await roleList())
getRoleList()

// 当前用户角色
const userStore = useUserStore()
const userRoleTitleList = ref([])
console.log('userStore.userInfo', userStore)

userRoleTitleList.value = userStore.userInfo.role.map((item) => item.title)
// 关闭弹窗
const closed = () => emits('update:modelValue', false)
//
const onConfirm = async () => {
  // 处理数据结构
  const roles = userRoleTitleList.value.map((title) => {
    return allRoleList.value.find((role) => role.title === title)
  })
  // 角色更新成功
  emits('updateRole', props.userId, roles)
  closed()
}
</script>

<style scoped></style>
